package com.sfac.springCloudAccount.dao;


import org.apache.ibatis.annotations.*;
import org.sfac.account.entity.Resource;
import org.sfac.common.vo.Search;
import org.springframework.stereotype.Repository;

import java.util.List;


@Mapper
@Repository
public interface ResourceDao {

	@Insert("insert into account_resource (permission, create_date) values (#{permission}, #{createDate})")
	@Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
	void insertResource(Resource resource);
	
	@Update("update account_resource set permission = #{permission} where id = #{id}")
	void updateResource(Resource resource);
	
	@Delete("delete from account_resource where id = #{id}")
	void deleteResourceById(int id);

	@Select("select * from account_resource where id = #{id}")
	@Results(id="resourceResult", value={
			@Result(column="id", property="id"),
			@Result(column="id",property="roles",
					javaType=List.class,
					many=@Many(select="com.sfac.springCloudAccount.dao.RoleDao.getRolesByResourceId"))
	})
	Resource getResourceById(int id);
	
	@Select("select * from account_resource ar left join account_role_resource arr on ar.id = arr.resource_id "
			+ "where arr.role_id = #{roleId}")
	List<Resource> getResourcesByRoleId(int roleId);
	
	@Select("<script>"
			+ "select * from account_resource "
			+ "<where> "
			+ "<if test='keyword != \"\" and keyword != null'>"
			+ " and (permission like '%${keyword}%') "
			+ "</if>"
			+ "</where>"
			+ "<choose>"
			+ "<when test='sort != \"\" and sort != null'>"
			+ " order by ${sort} ${direction}"
			+ "</when>"
			+ "<otherwise>"
			+ " order by id desc"
			+ "</otherwise>"
			+ "</choose>"
			+ "</script>")
	List<Resource> getResourcesBySearchBean(Search search);
}
